package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.LifeTel;
import com.eportal.domain.Sysopt;
import com.eportal.service.LifeStrategyService;
import com.eportal.service.LifeTelService;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;

/**
 * SysOptServiceImpl
 * @author chencheng
 */

@Service("lifeTelService")
public class LifeTelServiceImpl  implements LifeTelService {
	 private Logger log = Logger.getLogger(SysOptServiceImpl.class);
	 private Map<String, Object> result = new HashMap<String, Object>();
	 
	 @Resource(name="dao")
	 private BaseDAO dao;
	 
	 @Autowired
	 private LifeStrategyService lifeStrategyService;
	 public HttpSession getSession() {
		 return ServletActionContext.getRequest().getSession();
	 }
	 
    @Override
    public LifeTel save(LifeTel lifeTel) throws Exception {
    	dao.save(lifeTel);
    	return lifeTel;
    }
    
    private void delete(Long id) {
    	LifeTel lifeTel = (LifeTel) dao.getById(LifeTel.class, id);
    	if (lifeTel != null) {
    		dao.delete(lifeTel);
		}
    }

    @Override
    public void delete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public LifeTel get(Long id) {
        return (LifeTel) dao.getById(LifeTel.class, id);
    }

    @Override
    public void update(LifeTel lifeTel) throws Exception {
    	try {
    		dao.update(lifeTel);
        } catch (Exception e) {
            log.error(this,e);
        }
        
    }

    @Override
    public List<Map<String, Object>> list(JqGridPager jqGridPager) {
    	 String sql = "select t.sid,t.communityid,t.cname,t.pic,t.addr,t.intro,t.remark,t.tel1,t.tel2,c.areacode,c.citycode,c.communityname,c.agtcode from life_tel t "
 		 		+ "left join t03_community c on t.communityid=c.sid left join t02_agtent a on c.agtcode=a.agtcode";
 	     return dao.query(sql, jqGridPager);
    }


	/**
     * 便民电话保存
     */
    @LogAnnotation(operateDescribe="便民电话保存")  
    public Map<String, Object> addMethod(LifeTel lifeTel) {
        String msg = ValidateUtil.validate(lifeTel);
        if (msg == null || msg.trim().length() == 0) {
            try {
            	int userRole =  (Integer) getSession().getAttribute("userRole");
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	if (userRole == 1 || userRole == 2 || userRole == 21) {
            		lifeTel.setdType("1");
            	}else if (userRole == 3 || userRole == 4) {
            		lifeTel.setdType("2");
            		lifeTel.setAgtCode(user.getAgtCode());
            		if("0".equals(lifeTel.getAcceptRange())){//页面上的全部小区的意思是合作方下的全部小区
            			lifeTel.setAcceptRange("1");
            			lifeTel.setAcceptAgtCode(","+user.getAgtCode()+",");
            		}else if(StringUtils.isNotBlank(lifeTel.getAcceptAgtCode())){//如果选择了部分小区，但是又全选了小区
            			lifeTel.setAcceptRange("1");
            		}
            	}else if (userRole == 5 || userRole == 6) {
            		lifeTel.setdType("3");
            		lifeTel.setAgtCode(user.getAgtCode());
            		lifeTel.setCommunityId(user.getCommunityId());
            		lifeTel.setAcceptRange("2");//部分小区。自己的小区
            		lifeTel.setAcceptAgtCode("");
            		lifeTel.setAcceptCommunityId(","+user.getCommunityId()+",");
            	}
            	
            	lifeTel.setStatus("1");
            	lifeTel.setcUserName(Long.toString(user.getSid()));
            	lifeTel.setcTime(new Timestamp(System.currentTimeMillis()));
            	save(lifeTel);
            	result.put("objectId", lifeTel.getSid());
                result.put("code", 1);
                result.put("msg", "操作成功");
            } catch (Exception e) {
                log.error("添加便民电话失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
        	result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }

	/**
     * 便民电话更新保存
     */
    @LogAnnotation(operateDescribe="便民电话更新")  
    public Map<String, Object> updateMethod(LifeTel lifeTel) {
        String msg = ValidateUtil.validate(lifeTel);
        result.put("objectId", lifeTel.getSid());
        if (msg == null || msg.trim().length() == 0) {
            try {
            	LifeTel entity = get(lifeTel.getSid());
            	entity.setPriority(lifeTel.getPriority());
            	if (StringUtils.isNotBlank(lifeTel.getPic())) {
            		entity.setPic(lifeTel.getPic());
				}
            	
            	int userRole =  (Integer) getSession().getAttribute("userRole");
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	if (userRole == 1 || userRole == 2 || userRole == 21) {
            		entity.setAcceptAgtCode(lifeTel.getAcceptAgtCode());
        			entity.setAcceptCommunityId(lifeTel.getAcceptCommunityId());
        			entity.setAcceptRange(lifeTel.getAcceptRange());
            	}else if (userRole == 3 || userRole == 4) {
            		if("0".equals(lifeTel.getAcceptRange()) || lifeTel.getAcceptAgtCode().indexOf(","+user.getAgtCode()+",") >-1){//页面上的全部小区的意思是合作方下的全部小区，或者如果选择了部分小区，但是又全选了小区
            			entity.setAcceptRange("1");
            			//增加自己的合作方
            			String newagt = lifeStrategyService.getNoRepeat(user.getAgtCode(),entity.getAcceptAgtCode());
            			if (StringUtils.isNotBlank(entity.getAcceptAgtCode())){
            				entity.setAcceptAgtCode(entity.getAcceptAgtCode()+newagt);
            			}else{
            				entity.setAcceptAgtCode(newagt);
            			}
            			//减去所有的cmou
            			String communitys = lifeStrategyService.getCommunityId(user.getAgtCode());
            			String newcommunitys = lifeStrategyService.offNoRepeat(communitys,entity.getAcceptCommunityId());
            			entity.setAcceptCommunityId(newcommunitys);
            		}else{//部分
            			entity.setAcceptRange("2");
            			//减去自己的agt
            			String newagt =  lifeStrategyService.offNoRepeat(user.getAgtCode(),entity.getAcceptAgtCode());
            			entity.setAcceptAgtCode(newagt);
            			//减去所有的cmou
            			String communitys = lifeStrategyService.getCommunityId(user.getAgtCode());
            			String newcommunitys = lifeStrategyService.offNoRepeat(communitys,entity.getAcceptCommunityId());
            			//增加部分comu
            			String newcommunity = lifeStrategyService.getNoRepeat(lifeTel.getAcceptCommunityId().substring(1,lifeTel.getAcceptCommunityId().length()-1),newcommunitys);
            			if (StringUtils.isNotBlank(entity.getAcceptCommunityId())) {
            				entity.setAcceptCommunityId(newcommunitys+newcommunity);
						}else{
							entity.setAcceptCommunityId(","+newcommunity);
						}
            		}
            	}else if (userRole == 5 || userRole == 6) {
            		//分配范围不变
            	}
            	
            	entity.setcName(lifeTel.getcName());
            	entity.setAddr(lifeTel.getAddr());
            	entity.setIntro(lifeTel.getIntro());
            	entity.setTel1(lifeTel.getTel1());
            	entity.setTel2(lifeTel.getTel2());
            	entity.setRemark(lifeTel.getRemark());
                update(entity);
                result.put("code", 1);
                result.put("msg", "操作成功");
            } catch (Exception e) {
                log.error("修改便民电话失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
        	result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }

	
	 /**
     * 便民电话删除
     */
	@Override
    @LogAnnotation(operateDescribe="便民电话删除")  
    public Map<String, Object> deleteMethod(String ids) {
        try {
        	result.put("objectId", ids);
            String[] sparams = ids.split(",");
            for (String s : sparams) {
            	delete(Long.parseLong(s));
            }
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("删除便民电话失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
    }

	@Override
	public List<Map<String, Object>> queryBySql(String where) {
		StringBuffer sql = new StringBuffer();
		sql.append("select t.agtcode,t.agtname,c.agtCode,c.csid,c.ccomuname from T02_AGTENT t left join (select c.agtcode,XMLAGG(XMLELEMENT(E, c.sid || ',')).EXTRACT('//text()').getclobval() as csid,XMLAGG(XMLELEMENT(E, c.communityname || ',')).EXTRACT('//text()').getclobval() as ccomuname from t03_community c group by c.agtcode) c on t.agtcode=c.agtcode left join t02_agtent a on c.agtcode=a.agtcode");
		if (StringUtils.isNotBlank(where)) {
			sql.append(where);
		}
		return dao.queryBySql(sql.toString());
	}
	

}
